package com.example.exchange.common;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;

public class CommonResponse<T> extends HashMap<String, Object> implements Serializable {


  private static final String MESSAGE = "message";

  private static final String SUCCESS = "success";

  private static final String DATA = "data";

  private static final String REDIRECT = "redirect";

  private static final String EMPTY = "";

  private static final String TIMESTAMP = "timestamp";

  // private static final String DURATION = "duration";
  private Long startTime;
  private Long endTime;


  private CommonResponse() {
    super();
    this.put(SUCCESS, false);
    this.put(TIMESTAMP, System.nanoTime());

  }

  public static CommonResponse createCommonResponse() {
    CommonResponse commonResponse = new CommonResponse();
    commonResponse.success();
    return commonResponse;
  }

  public static CommonResponse createCommonResponse(Object data) {
    CommonResponse commonResponse = new CommonResponse();
    commonResponse.success();
    commonResponse.setData(data);
    return commonResponse;
  }

  public boolean isSuccess() {
    return get(SUCCESS) != null && (Boolean) get(SUCCESS);
  }

  public String getMessage() {
    if (get(MESSAGE) != null) {
      return (String) get(MESSAGE);
    }
    return EMPTY;
  }

  public CommonResponse success() {
    this.put(SUCCESS, true);
    this.put(TIMESTAMP, System.currentTimeMillis());
    //setDuration();
    return this;
  }

  public CommonResponse success(String message) {
    this.put(SUCCESS, true);
    this.put(MESSAGE, message);
    this.put(TIMESTAMP, System.currentTimeMillis());
    //setDuration();
    return this;
  }

  public CommonResponse fail(String message) {
    this.put(SUCCESS, false);
    this.put(MESSAGE, message);
    this.put(TIMESTAMP, System.currentTimeMillis());
    //setDuration();
    return this;
  }

  public CommonResponse redirect(String url) {
    this.put(REDIRECT, url);
    this.put(TIMESTAMP, System.currentTimeMillis());
    //setDuration();
    return this;
  }

  public CommonResponse setData(Object data) {
    return putData(DATA, data);
  }

  public CommonResponse putData(String key, Object data) {
    this.put(key, data);
    return this;
  }

  private void setDuration() {
    Long duration = 0L;
    if (startTime != null && endTime != null && endTime >= startTime) {
      duration = endTime - startTime;
    }
    BigDecimal diff = BigDecimal.valueOf(duration, 10);//秒级差值
    DecimalFormat fmt = new DecimalFormat("#.#########");//输出格式化
    //this.put(DURATION,fmt.format(diff));
  }

  public Long getStartTime() {
    return startTime;
  }

  public void setStartTime(Long startTime) {
    this.startTime = startTime;
  }

  public Long getEndTime() {
    return endTime;
  }

  public void setEndTime(Long endTime) {
    this.endTime = endTime;
  }
}
